import { Response } from "express"
import { OkPacket, ResultSetHeader } from "mysql2"
import { checkError } from "./token"
import { FN } from "@Tea/model"

export const initReturn = (data: any, code?: number, message?: string) => ({
  code: code ? code : 1,
  data,
  message: message ? message : ""
})

export const checkSqlHandl = (result: ResultSetHeader) =>{
  return {
    succesFlag: result.affectedRows !== 0 ? 1 : 0,
    info: result.info
  }
}

// 用于检测改变行数的sql
export const useCheckAndResponse = (res: Response, result: ResultSetHeader, succesMsg:string, returnInsert = false) => {
  try {
    const { succesFlag, info } = checkSqlHandl(result)
    res.send({
      code: succesFlag,
      msg: succesFlag ? succesMsg : info,
      data: returnInsert ? result.insertId : undefined
    })

    return !!succesFlag
  } catch (e) {
    res.status(500).send({
      code: 0,
      msg:checkError(e)
    })
  }
}
export const catchError = async(res: Response, callBack: FN) => {
  try { 
    return callBack() 
  } catch (e) {
    res.status(500).send({
      code: 0,
      msg:checkError(e)
    })
  }
}